package com.learn.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * @author wangxing
 * @version 2020/8/9 15:31 Administrator
 */
public class ThreadLocalLearn {
    static ThreadLocal<String> t1 = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        threadLocalCanNotGetDistinctThreadData();
    }

    /**
     * ThreadLocal 不能从不同线程中获取数据
     *     public void set(T value) {
     *         Thread t = Thread.currentThread();
     *         ThreadLocalMap map = getMap(t);
     *         if (map != null)
     *             map.set(this, value);
     *         else
     *             createMap(t, value);
     *     }
     *     原因在于ThreadLocal中是将当前线程做为key去进行保存数据的,所以只能获取当前线程对应的数据
     */
    public static void threadLocalCanNotGetDistinctThreadData() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t1.set("KingStar");
        });
        Thread thread1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(t1.get());
        });
        thread.start();
        thread.join();
        thread1.start();
        thread1.join();
    }
}
